﻿using System;
using System.ComponentModel.Composition;
using Caliburn.Micro;
using Microsoft.Win32;

namespace PocketBook.Tasks
{
    public class SelectFileWith<TDialog> : ISelectFileTask where TDialog : FileDialog, new()
    {
        public event EventHandler<ResultCompletionEventArgs> Completed;

        [Import]
        public IWindowManager WindowManager { get; set; }

        public bool CheckIfFileExists { get; set; }

        public string FileName { get; set; }

        public string Filter { get; set; }

        public string InitialDirectory { get; set; }

        public string DefaultExtension { get; set; }

        public void Execute(ActionExecutionContext context)
        {
            var dialog = new TDialog
                         {
                             InitialDirectory = InitialDirectory,
                             FileName = FileName,
                             Filter = Filter,
                             DefaultExt = DefaultExtension,
                             CheckFileExists = CheckIfFileExists
                         };

            var result = dialog.ShowDialog();
            FileName = result == true ? dialog.FileName : String.Empty;

            Completed(this, new ResultCompletionEventArgs { WasCancelled = result == false });
        }
    }
}